package com.xingxue.filter;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xingxue.service.UserService;
import com.xingxue.service.UserServiceImpl;
import com.xingxue.util.JdbcUtil;

/**
 * 假设现在要过滤某些jsp
 */
@WebFilter("/index.jsp")
public class AutoLoginFilter implements Filter {
	
	private UserService userService = JdbcUtil.createProxy(new UserServiceImpl(), UserService.class);

	public void init(FilterConfig fConfig) throws ServletException {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		// session中已经有登录标记的话，不用从cookie检查了
		Object isLogin = session.getAttribute("login");
		if(isLogin != null) {
			chain.doFilter(request, response);
			return;
		}
		
		Cookie[] cookies = req.getCookies();
		Cookie auto = null;
		for(Cookie c: cookies) {
			if(c.getName().equals("token")) {
				auto = c;
				break;
			}
		}
		
		if(auto == null) {
			System.out.println("[调试信息] 没有自动登录cookie，跳转至登录页面");
			resp.sendRedirect("login.jsp");
			return;
		}
		
		String value = URLDecoder.decode(auto.getValue(),"utf-8");
		String[] a = value.split("\\|");
		if(value == null || a.length != 2) {
			System.out.println("[调试信息] token格式不正确，跳转至登录页面");
			resp.sendRedirect("login.jsp");
			return;
		}
		
		if(! userService.isTokenValid(a[0], a[1])) {
			System.out.println("[调试信息] token不合法(值或者过期时间)，跳转至登录页面");
			resp.sendRedirect("login.jsp");
			return;
		}
		
		System.out.println("[调试信息] 自动登录成功");
		chain.doFilter(request, response);
	}

}
